package com.example.multiReactorMultiThread;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Acceptor implements Runnable {

    private Selector selector;
    private ServerSocketChannel serverSocketChannel;
    private ExecutorService executorService = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
    private SubReactor[] reactors ;
    private int subReactorNums;
    private int index;

    public Acceptor(Selector selector,ServerSocketChannel serverSocketChannel,int subReactorNums) throws IOException {
        this.selector=selector;
        this.serverSocketChannel=serverSocketChannel;
        this.subReactorNums=subReactorNums;
        this.reactors=new SubReactor[this.subReactorNums];
        for (int i = 0; i < this.subReactorNums; i++) {
            reactors[i]=new SubReactor();
        }
        this.index=0;
    }

    @Override
    public void run() {
        try {

            SocketChannel socketChannel = serverSocketChannel.accept();
            if (socketChannel!=null){
                socketChannel.write(ByteBuffer.wrap("Multiply Reactor Pattern \r\n reactor>".getBytes()));
                System.out.println(Thread.currentThread().getName()+" register server");
            }
            SubReactor reactor = reactors[index++];
            index=index%subReactorNums;
            reactor.registry(new Handler(socketChannel,executorService));
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
